#include <QTimer>

#include "NetworkManager.h"

NetworkManager::NetworkManager(const QList<std::string> &list):m_pingList(list)
{
#ifdef __linux__
    connect(&m_manager,&QNetworkConfigurationManager::onlineStateChanged,this,&NetworkManager::onLinuxState);
#else
    m_pingTimer = new QTimer;
    m_pingTimer->setSingleShot(true);
    m_ping = new NetworkPing;

    connect(m_ping,&NetworkPing::pingState,this,&NetworkManager::onWinMacState);
    connect(m_pingTimer,&QTimer::timeout,[this](){
        m_ping->ping(m_pingList);
    });
#endif
}

void NetworkManager::start()
{
#ifdef __linux__
#else
    m_pingTimer->start(1500);
#endif
    isEmitSignal = true;
}

void NetworkManager::stop()
{
#ifdef __linux__
#else
    m_ping->exitPing();
#endif
    isEmitSignal = false;
}

void NetworkManager::onLinuxState(bool isOnline)
{
    if (!isEmitSignal)
        return;

    emit onlineState(isOnline);
}

void NetworkManager::onWinMacState(NetworkPingState state)
{
#ifdef __linux__
#else
    if (!isEmitSignal)
        return;

    bool netState = m_lastNetState;
    if (state == NETWORK_PING_OK) {
        m_pingErrorCount = 0;
        m_lastNetState = true;
        if (netState != m_lastNetState) {
            emit onlineState(true);
        }
    } else {
        if (++m_pingErrorCount > 2) {
            m_lastNetState = false;
            if (netState != m_lastNetState) {
                emit onlineState(false);
            }
        }
    }
#endif
}
